package edu.gdkm.observer.impl;

import edu.gdkm.observer.Observer;
import edu.gdkm.observer.Subject;

import java.util.ArrayList;
import java.util.List;

public class WeatherData implements Subject {

    private List<Observer> observers;
    private float temperature;
    private float humidity;
    private float pressure;

    public WeatherData(){
        observers = new ArrayList<>();
    }

    /**
     * 注册观察者
     */
    @Override
    public void registerObserver(Observer observer) {
        if (observer == null) {
            throw new NullPointerException("observer not null !");
        }
        observers.add(observer);
    }

    /**
     * 当观察者想取消注册，我们只需要从ArrayList中删除即可
     * @param observer 观察者
     */
    @Override
    public void removeObserver(Observer observer) {
        observers.remove(observer);
    }

    @Override
    public void notifyObServers() {
        observers.forEach(observer -> observer.update(temperature, humidity, pressure));
    }

    /**
     * 当从气象站得到更新的观测值时，我们通知观察者
     */
    public void measurementsChanged(){
        notifyObServers();
    }

    public void setMeasurements(float temperature, float humidity, float pressure){
        this.temperature = temperature;
        this.humidity = humidity;
        this.pressure = pressure;
        measurementsChanged();
    }


    public List<Observer> getObservers() {
        return observers;
    }

    public float getTemperature() {
        return temperature;
    }

    public float getHumidity() {
        return humidity;
    }

    public float getPressure() {
        return pressure;
    }

}
